package main.string;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;

import java.io.Serializable;
import java.lang.reflect.Type;

/**
 * @author ChengGM
 * @create 2016-12-27 12:08
 **/
public class jsonTest {
    public static Gson gson;

    static {
        GsonBuilder gb = new GsonBuilder();
        //禁止html转义
        gb.disableHtmlEscaping();
        //处理下划线分割的json字符串（生成json字符串时候将驼峰转化为下划线，解析json时候将下划线转为驼峰）
        gb.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        //设置json时间格式
        gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
        gson = gb.create();
    }
    @Test
    public void test() {
        String s ="{\"item_id\":3,\"item_name\":\"保税 【2盒含税】英国牛栏Cow & Gate奶粉1-4段\"}";
//                "{\"item_id\":4116,\"item_name\":\"保税 【2盒含税】英国牛栏Cow & Gate奶粉1-4段\"}";
        //判断字符串中是否有&，有就替换掉
//        if(s.contains("&")
////                s.indexOf("&")>0
//                ){
//            s = s.replace("&","&amp");
//        }
        Type type = new com.google.gson.reflect.TypeToken<Item>() {
        }.getType();
        Item item = null;
        try {
           item = (Item) gson.fromJson(s, type);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(item.toString());
        System.out.println(gson.toJson(item));
    }
    @Test
    public void test2(){
        Gson gson = new Gson();
        Item item = new Item();
        item.setItemId(3L);
        item.setItemName("hello moto");
        String out = gson.toJson(item);
        System.out.println(out);
    }
}

    class Item implements Serializable{
        private Long itemId;
        private String itemName;

        public void Item() {
        }

        public Long getItemId() {
            return itemId;
        }

        public void setItemId(Long itemId) {
            this.itemId = itemId;
        }

        public String getItemName() {
            return itemName;
        }

        public void setItemName(String itemName) {
            this.itemName = itemName;
        }

        @Override
        public String toString() {
            return "Item{" +
                    "itemId=" + itemId +
                    ", itemName='" + itemName + '\'' +
                    '}';
        }
    }

